package com.xtaifghy.wugui;

import com.xtaifghy.wugui.util.Util;

import java.util.ArrayList;
import java.util.Random;

public class GameState2 implements GameStateInterface{
    private boolean [] state = {true,true,true,true,true,true,true,true};
    private boolean [] goalState = {false,true,false,false,false,false,false,false};
    Random rand = new Random();
    private static final ArrayList<boolean[]> actionSequence = getAllActionSequence();
    private static final int[][] actions={
            {0,1,3},//1
            {0,1,2},//2
            {1,2,4},//3
            {0,5,3},//4
            {1,4,6,3},//5
            {2,4,7},//6
            {6,5,3},//7
            {6,5,7},//8
            {6,4,7},//9
    };

    @Override
    public void doAction(int a){
        if(a<0||a>actions.length)return;
        for (int i:actions[a]) {
            state[i]=!state[i];
        }
    }

    @Override
    public boolean testState(){
        for (int i = 0; i < state.length; i++) {
            if(state[i]!=goalState[i]) return false;
        }
        return true;
    }

    /*
    *返回所有512种可能的动作队列
     */
    private static ArrayList<boolean[]> getAllActionSequence(){
        ArrayList<boolean[]> actionSequence = new ArrayList<>();
        for (int i = 0; i < 512; i++) {
            actionSequence.add(Util.intToBArr(i,9));
        }
        return actionSequence;
    }

    public GameState2() {
        randomGoalState();
    }

    //testPath判断给定初始状态state是否可经由路径path到达目标状态goalState
    private static boolean testPath(boolean[] initState, boolean[] goalState, boolean[]path){
        boolean[] tempState = initState.clone();
        for (int i = 0; i < path.length; i++) {
            if(path[i]) {
                for (int j:actions[i]) {
                    tempState[j] = !tempState[j];
                }
            }
        }
        for (int i = 0; i < tempState.length; i++) {
            if(tempState[i]!=goalState[i]) return false;
        }
        return true;
    }

    @Override
    public ArrayList<boolean[]> getPaths(){
        ArrayList<boolean[]> paths = new ArrayList<>();
        for (int i = 0; i < 512; i++) {
            boolean[] path = Util.intToBArr(i,9);
            if(testPath(state,goalState,path)){
                paths.add(path);
                //break;//找到1个解之后，停止
            }
        }
        return paths;
    }

    @Override
    public void randomGoalState(){
        for (int i = 0; i < goalState.length; i++) {
            goalState[i] = rand.nextBoolean();
        }
    }

    @Override
    public void setState(boolean[] state) {
        this.state=state.clone();
    }

    @Override
    public boolean[] getState(){
        return state.clone();
    }

    @Override
    public void setGoalState(boolean[] goalState) {
        this.goalState = goalState.clone();
    }

    @Override
    public boolean[] getGoalState(){
        return goalState.clone();
    }
}
